/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    struct ListNode *curA=headA;
    struct ListNode * curB=headB;
    int countA=1;
    while(curA->next!=NULL)
    {
       countA++;
       curA=curA->next;
    }
    int countB=1;
    while(curB->next!=NULL)
    {
        countB++;
        curB=curB->next;
    }
      if(curB!=curA)
      {
          return NULL;
      }
      struct ListNode*longNode=headA;
      struct ListNode* shortNode=headB;
      if(countA<countB)
      {
          longNode=headB;
          shortNode=headA;
      }
      int gap=abs(countB-countA);
      while(gap--)
      {
          longNode=longNode->next;
      }
      while(longNode!=shortNode)
      {
          longNode=longNode->next;
          shortNode=shortNode->next;
      }
      return longNode;

}

struct ListNode *detectCycle(struct ListNode *head) {
    struct ListNode*fast=head;
    struct ListNode* slow=head;
    while(fast&&fast->next)
    {
        fast=fast->next->next;
        slow=slow->next;
        if(fast==slow)
        {
            struct ListNode* meet=fast;
            struct ListNode* next=meet->next;
            meet->next=NULL;
            return getIntersectionNode(head,next);
            
        }
    }
    return NULL;
}
